

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=&#34;auto&#34;>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/2.jpg">
  <link rel="icon" type="image/png" href="/img/2.jpg">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="">
  <meta name="author" content="K">
  <meta name="keywords" content="">
  <title>JavaScript-ajax请求 - K</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
    
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_kmeydafke9r.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.2.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>かい</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;</a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" href="javascript:">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner intro-2" id="background" parallax=true
         style="background: url('/img/1.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container page-header text-center fade-in-up">
            <span class="h2" id="subtitle">
              
            </span>

            
              <div class="mt-3">
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2020-11-05 13:23" pubdate>
        2020年11月5日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      1.1k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      12
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto" id="post">
            <!-- SEO header -->
            <h1 style="display: none">JavaScript-ajax请求</h1>
            
            <div class="markdown-body" id="post-body">
              <h2 id="ajax"><a href="#ajax" class="headerlink" title="ajax"></a>ajax</h2><ul>
<li>为什么要使用ajax<ul>
<li>传统网站中会有一些缺陷</li>
<li>网速慢的时候，页面加载时间长，用户只能等待</li>
<li>表单提交后，如果一箱内容不合格，就需要重新填写表单内容，体验不好</li>
<li>页面跳转，会重新加载页面，浪费资源，增加用户等待时间</li>
</ul>
</li>
<li>ajax的优点<ul>
<li>是浏览器提供的一套方法，可以实现页面无刷新更新数据，提高用户浏览网站的体验<br>（就是用户在浏览网页的过程中局部的更新页面的内容）</li>
</ul>
</li>
<li>应用场景<ul>
<li>页面上拉加载数据</li>
<li>列表数据无刷新分页</li>
<li>表单数据验证</li>
<li>搜索框提示文字下载列表</li>
</ul>
</li>
</ul>
<h2 id="ajax运行环境"><a href="#ajax运行环境" class="headerlink" title="ajax运行环境"></a>ajax运行环境</h2><ul>
<li>ajax技术需要运行在网站环境中才能够生效</li>
</ul>
<h2 id="ajax运行原理"><a href="#ajax运行原理" class="headerlink" title="ajax运行原理"></a>ajax运行原理</h2><ul>
<li>ajax相当于浏览器发送请求与接收响应的代理人，在不影响用户浏览页面的情况下，局部的更新页面数据，提高用户的体验</li>
</ul>
<h2 id="ajax对象的定义"><a href="#ajax对象的定义" class="headerlink" title="ajax对象的定义"></a>ajax对象的定义</h2> <pre><code class="hljs vala"><span class="hljs-meta"># 1.创建ajax对象</span>
<span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLrequest(); <span class="hljs-comment">// 这就是创建ajax实例对象</span>
<span class="hljs-meta"># 2.告诉ajax请求地址以及请求方式</span>
xhr.open(<span class="hljs-string">&#x27;get&#x27;</span>,<span class="hljs-string">&#x27;http:127.0.0.1&#x27;</span>);
<span class="hljs-meta"># xhr.open(&#x27;请求方式&#x27;,&#x27;请求地址&#x27;);</span>
<span class="hljs-meta"># 3.发送请求</span>
xhr.send();
<span class="hljs-meta"># 4.获取服务端给客户端的响应数据</span>
xhr.addEventlistener(<span class="hljs-string">&#x27;load&#x27;</span>,function()&#123;
    console.log(xhr.responseText);
&#125;);
<span class="hljs-meta"># 当服务端响应了客户端，客户独断就会自动调用 onload事件处理函数</span></code></pre>
<ul>
<li>服务端响应数据格式<ul>
<li>在真实项目中，服务器大多数会以json对象作为响应数据格式，当客户端拿到响应数据时，要将json数据和html字符串进行拼接，然后将拼接的结果显示在页面中<br>（这里先不讲后端，另写文章）</li>
</ul>
</li>
</ul>
<h2 id="请求参数的传递"><a href="#请求参数的传递" class="headerlink" title="请求参数的传递"></a>请求参数的传递</h2><ul>
<li><p>get请求\post请求</p>
<ul>
<li>传统网站是通过表单提交参数</li>
<li>ajax是需要自己拼接请求参数的，根据请求方式的不同，将请求参数放到对应的位置上</li>
</ul>
</li>
<li><p>格式</p>
<ul>
<li><p>参数名称=值&amp;参数名称=值</p>
</li>
<li><p>对于get请求，参数是放到请求地址后面的，并且用?进行分割</p>
<pre><code class="hljs awk"><span class="hljs-comment"># get请求是这样的</span>
https:<span class="hljs-regexp">//</span>www.baidu.com/?user=lmk&amp;passwd=kml</code></pre></li>
</ul>
</li>
<li><p>get请求参数</p>
<pre><code class="hljs csharp"><span class="hljs-meta"># 先获取元素 例如div元素表单元素等等（这里不多演示）</span>

<span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest(); <span class="hljs-meta"># 创建ajax对象</span>
<span class="hljs-meta"># 表单值获取 （在html标签中定义了2个input标签）</span>
<span class="hljs-keyword">var</span> namev = user.<span class="hljs-keyword">value</span>;
<span class="hljs-keyword">var</span> agev = age.<span class="hljs-keyword">value</span>;

<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = <span class="hljs-string">&#x27;?user=&#x27;</span>+namev+<span class="hljs-string">&#x27;&amp;age=&#x27;</span>+agev <span class="hljs-meta"># 拼接请求参数</span>
<span class="hljs-meta"># 配置ajax准备发送get请求到后端服务器上（这里用的falsk）</span>
xhr.open(<span class="hljs-string">&#x27;get&#x27;</span>,<span class="hljs-keyword">value</span>,<span class="hljs-literal">true</span>)
  <span class="hljs-meta"># 这里value是请求参数，我在falsk后端试了一下，这里写请求参数就可以把参数传递给后端，如果在node.js中要写后端的ip地址加参数</span>
  <span class="hljs-meta"># true的意思是是否为异步请求，true是 flase否</span>

xhr.send(); <span class="hljs-meta"># 发送请求</span>
  <span class="hljs-meta"># 服务器接收请求，给客户端发送响应数据</span>
<span class="hljs-meta"># 获取服务端响应的数据</span>
xhr.addEventListener(<span class="hljs-string">&#x27;load&#x27;</span>,function()&#123;
    console.log(xhr.responseText);
&#125;)</code></pre>

</li>
</ul>
<ul>
<li>post请求参数<ul>
<li>post请求的请求餐数和get不一样，不是放到请求地址中，而是要放到请求体当中</li>
<li>只需要将请求参数放到send方法中即可<pre><code class="hljs csharp"><span class="hljs-meta"># 先获取元素 例如div元素表单元素等等（这里不多演示）</span>

<span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest(); <span class="hljs-meta"># 创建ajax对象</span>
<span class="hljs-keyword">var</span> userv = user.<span class="hljs-keyword">value</span> <span class="hljs-meta"># 获取表单值</span>
<span class="hljs-keyword">var</span> agev = age.<span class="hljs-keyword">value</span> <span class="hljs-meta"># 获取表单值</span>
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = <span class="hljs-string">&#x27;user=&#x27;</span>+userv+<span class="hljs-string">&#x27;&amp;age=&#x27;</span>+agev; <span class="hljs-meta"># 拼接请求参数</span>
xhr.open(<span class="hljs-string">&#x27;post&#x27;</span>,<span class="hljs-string">&#x27;&#x27;</span>); <span class="hljs-meta"># 配置ajax请求 </span>
  <span class="hljs-meta"># 请求为 post请求 第二个参数不写就默认为/路径 默认为true（异步）</span>
  <span class="hljs-meta"># node.js要写请求地址（这里由于是flask只写请求路径即可）</span>
xhr.setRequestHeader(<span class="hljs-string">&#x27;Content-type&#x27;</span>,<span class="hljs-string">&#x27;application/x-www-form-urlencoded&#x27;</span>); <span class="hljs-meta"># post请求中必须要设置请求参数的格式类型</span>
xhr.send(<span class="hljs-keyword">value</span>) <span class="hljs-meta"># 发送post请求 ，参数</span>
    
<span class="hljs-meta"># 服务器接收请求，给客户端发送响应数据</span>
<span class="hljs-meta"># 获取服务端响应的数据</span>
xhr.addEventListener(<span class="hljs-string">&#x27;load&#x27;</span>,function()&#123;
  console.log(xhr.responseText);
&#125;)</code></pre>

</li>
</ul>
</li>
</ul>
<h2 id="get请求和post请求的区别"><a href="#get请求和post请求的区别" class="headerlink" title="get请求和post请求的区别"></a>get请求和post请求的区别</h2><ul>
<li>post请求必须要请求报文中，明确设置请求参数内容的类型</li>
</ul>

            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/javascript/">javascript</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/ajax/">ajax</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章是以学习为目的，如果有不对的地方可以一起交流沟通共同学习 邮箱:1248287831@qq.com！</p>
              
              
                <div class="post-prevnext row">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2020/11/05/%E5%89%8D%E7%AB%AF%E8%AF%B7%E6%B1%82-ajax%E5%8F%82%E6%95%B0/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">JavaScript-ajax请求配置</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2020/11/04/%E5%89%8D%E7%AB%AF%E5%B8%83%E5%B1%80-flex%E5%B8%83%E5%B1%80/">
                        <span class="hidden-mobile">前端布局-flex布局</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://space.bilibili.com/39165374" target="_blank" rel="nofollow noopener"><span>LMK</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: '#post-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "JavaScript-ajax请求&nbsp;",
      ],
      cursorChar: "_",
      typeSpeed: 70,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>















</body>
</html>
